#import "XLWebViewController.h"
#import "XLJSHandler.h"
#import "HeaderModel.h"
#import "AESCipher.h"
#import <YYKit.h>
#import "XMNShareMenu.h"
#import "ShareManager.h"
#define WebMessageNamePaySuccess @"pay_back"
@interface XLWebViewController () <WKNavigationDelegate, WKScriptMessageHandler , WKUIDelegate>
@property (nonatomic,strong) XLJSHandler * jsHandler;
@property (nonatomic,assign) double lastProgress;
@end
@implementation XLWebViewController
-(instancetype)initWithUrl:(NSString *)url {
    self = [super init];
    if (self) {
        self.url = url;
        _progressViewColor = [UIColor colorWithHexString:@"0485d1"];
    }
    return self;
}
-(void)setUrl:(NSString *)url
{
    if (_url != url) {
        _url = url;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
        NSString *headerContentStr = [[HeaderModel new] modelToJSONString];
        NSString *headerAESStr = aesEncrypt(headerContentStr);
        [request setValue:headerAESStr forHTTPHeaderField:@"header-encrypt-code"];
        [self.webView loadRequest:request];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:WebMessageNamePaySuccess];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initWKWebView];
    if (@available(iOS 11.0, *)){
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
#pragma mark 初始化webview
-(void)initWKWebView
{
    WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];
    configuration.preferences.javaScriptEnabled = YES;
    _webConfiguration = configuration;
    _jsHandler = [[XLJSHandler alloc]initWithViewController:self configuration:configuration];
    self.webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:configuration];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:WebMessageNamePaySuccess];
    self.webView.UIDelegate = self;
    self.webView.height = self.view.height - kTopHeight;
    _webView.navigationDelegate = self;
    _webView.backgroundColor = [UIColor clearColor];
    _webView.allowsBackForwardNavigationGestures =YES;
    _webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:_webView];
    _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    _progressView.tintColor = _progressViewColor;
    _progressView.trackTintColor = [UIColor clearColor];
    _progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 3.0);
    [_webView addSubview:_progressView];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
    NSString *headerContentStr = [[HeaderModel new] modelToJSONString];
    NSString *headerAESStr = aesEncrypt(headerContentStr);
    [request setValue:headerAESStr forHTTPHeaderField:@"header-encrypt-code"];
    [_webView loadRequest:request];
}
#pragma mark 开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"%s",__func__);
    [self evaluateMyJavaScript:webView];
    NSString *curUrl = [webView.URL absoluteString];
    NSMutableString *curMstr = [NSMutableString stringWithString:curUrl];
    NSRange curSubstr = [curMstr rangeOfString:@"show_prog=1"]; 
    if ([curUrl hasPrefix:@"tel:"])
    {
        NSMutableString *mstr = [NSMutableString stringWithString:curUrl];
        NSRange substr = [mstr rangeOfString:@"tel:"]; 
        if (substr.location != NSNotFound)
        {
            [mstr deleteCharactersInRange:substr];
        }
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",mstr];
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        [[UIApplication sharedApplication] openURL:url];
    }
    if([curUrl containsString:@"cuckoo://open_custom_service_qq"])
    {
        [self gotoQQ];
        return;
    }
    if([curUrl containsString:@"cuckoo://invite_share"])
    {
        [self shareAction];
        return;
    }
    if([curUrl containsString:@"cuckoo://open_vip_page"])
    {
        [self gotoVIP];
        return;
    }
}
- (void)gotoVIP {
    XLWebViewController *webview = [XLWebViewController new];
    NSString * urlstring = KGlobalVariable.appmodel.app_h5.vip_url;
    urlstring = [NSString stringWithFormat:@"%@?uid=%@&token=%@",urlstring,curUser.id,curUser.token];
    webview.url = urlstring;
    [self.navigationController pushViewController:webview animated:YES];
}
- (void)loadImageFinished:(UIImage *)image
{
    UIImage *img = image;
    CGImageRef imgRef = img.CGImage;
    CGFloat w = CGImageGetWidth(imgRef);
    CGFloat h = CGImageGetHeight(imgRef);
    UIImage *img1 = [UIImage imageNamed:@"bglogo"];
    CGImageRef imgRef1 = img1.CGImage;
    CGFloat w1 = CGImageGetWidth(imgRef1);
    CGFloat h1 = CGImageGetHeight(imgRef1);
    UIGraphicsBeginImageContext(CGSizeMake(w1, h1));
    [img1 drawInRect:CGRectMake(0, 0, w1, h1)];
    [img drawInRect:CGRectMake(w1/2-130, h1/2-160, 250, 250)];
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"01.png"];
    [UIImagePNGRepresentation(resultImg) writeToFile:filePath atomically:YES];
    CGImageRelease(imgRef);
    CGImageRelease(imgRef1);
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        [MBProgressHUD showTopTipMessage:ASLocalizedString(@"保存到相册啦")isWindow:YES];
        NSLog(@"success = %d, error = %@", success, error);
    }];
}
- (void)shareAction {
    NSArray* shareAry = @[@{kXMNShareImage:@"more_weixin",
                            kXMNShareHighlightImage:@"more_weixin_highlighted",
                            kXMNShareTitle:ASLocalizedString(@"微信")},
                          @{kXMNShareImage:@"more_circlefriends",
                    kXMNShareHighlightImage:@"more_circlefriends_highlighted",
                        kXMNShareTitle:ASLocalizedString(@"朋友圈")},
                          @{kXMNShareImage:@"more_icon_link",
                            kXMNShareTitle:ASLocalizedString(@"二维码")},
                          ];
    NSMutableArray *fullarr = [NSMutableArray arrayWithArray:shareAry];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 36)];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 21, headerView.frame.size.width-32, 15)];
    label.textColor = [UIColor colorWithRed:94/255.0 green:94/255.0 blue:94/255.0 alpha:1.0];;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:15];
    label.text = ASLocalizedString(@"分享");
    [headerView addSubview:label];
    XMNShareView *shareView = [[XMNShareView alloc] init];
    shareView.headerView = headerView;
    __weak __typeof(shareView)weakshareView = shareView;
    [shareView setSelectedBlock:^(NSUInteger tag, NSString *title) {
        if([title isEqualToString:ASLocalizedString(@"二维码")])
        {
            CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
            [filter setDefaults];
            NSString *string = [NSString stringWithFormat:@"%@/mapi/public/index.php/api/download_api/index?invite_code=%@",URL_main,curUser.id];
            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
            [filter setValue:data forKeyPath:@"inputMessage"];
            CIImage *image = [filter outputImage];
            QMUIDialogViewController *alert = [[QMUIDialogViewController alloc] init];
            alert.title = ASLocalizedString(@"二维码");
            UIImageView *imageview = [[UIImageView alloc] initWithImage:[self createNonInterpolatedUIImageFormCIImage:image withSize:180]];
            alert.contentView = imageview;
            alert.buttonBackgroundColor = KWhiteColor;
            [alert addCancelButtonWithText:ASLocalizedString(@"取消")block:^(QMUIDialogViewController *dialogViewController) {
                [dialogViewController hide];
            }];
            [alert addCancelButtonWithText:ASLocalizedString(@"保存到相册")block:^(QMUIDialogViewController *dialogViewController) {
                [self loadImageFinished:imageview.image];
                [dialogViewController hide];
                [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"已保存到相册")];
            }];
            [alert show];
        }
        else if([title isEqualToString:ASLocalizedString(@"微信")] || [title isEqualToString:ASLocalizedString(@"朋友圈")])
        {
            NSString *string = [NSString stringWithFormat:@"%@/mapi/public/index.php/api/download_api/index?invite_code=%@",URL_main,curUser.id];
            if([title isEqualToString:ASLocalizedString(@"朋友圈")])
            {
                [[ShareManager sharedShareManager] shareImageToPlatformType:UMSocialPlatformType_WechatTimeLine WhithUrl:string AndVC:self];
            }
            else
            {
                [[ShareManager sharedShareManager] shareImageToPlatformType:UMSocialPlatformType_WechatSession WhithUrl:string AndVC:self];
            }
        }
        [weakshareView dismissUseAnimated:NO];
    }];
    [shareView setupShareViewWithItems:fullarr];
    [shareView showUseAnimated:YES];
}
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
#pragma mark js请求oc
- (void)evaluateMyJavaScript:(WKWebView *)webView
{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"fun.js" ofType:nil];
    NSString *jsStr=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [webView evaluateJavaScript:jsStr completionHandler:nil];
}
-(void)backButtonClicked
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
    else {
        [super backBtnClicked];
    }
}
#pragma mark --进度条
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    [self updateProgress:_webView.estimatedProgress];
}
#pragma mark -  更新进度条
-(void)updateProgress:(double)progress{
    self.progressView.alpha = 1;
    if(progress > _lastProgress){
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
    }else{
        [self.progressView setProgress:self.webView.estimatedProgress];
    }
    _lastProgress = progress;
    if (progress >= 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.alpha = 0;
            [self.progressView setProgress:0];
            _lastProgress = 0;
        });
    }
}
#pragma mark --navigation delegate
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:WebMessageNamePaySuccess]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    }
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    [self alertMessage:message completionHandler:completionHandler];
}
- (void)alertMessage:(NSString *)message completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }];
    [alertController addAction:alertAction];
    [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}
- (UIViewController *)getCurrentVC {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
}
- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]) {
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        currentVC = rootVC;
    }
    return currentVC;
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = webView.title;
    [self updateProgress:webView.estimatedProgress];
    [self updateNavigationItems];
}
-(void)updateNavigationItems{
}
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if(webView != self.webView) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    [self updateNavigationItems];
    NSURL * url = webView.URL;
    UIApplication *app = [UIApplication sharedApplication];
    if ([url.scheme isEqualToString:@"tel"])
    {
        if ([app canOpenURL:url])
        {
            [app openURL:url];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    if ([url.absoluteString containsString:@"itunes.apple.com"])
    {
        if ([app canOpenURL:url])
        {
            [app openURL:url];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    if([url.absoluteString containsString:@"vip_api/buy_vip"])
    {
        if ([app canOpenURL:url])
        {
            [app openURL:url];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)gotoQQ {
    NSString *QQ = KGlobalVariable.appmodel.custom_service_qq;
    NSString *url = [NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",QQ];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
        if(!success)
        {
            [HUDHelper alert:[NSString stringWithFormat:@"QQ:%@",KGlobalVariable.appmodel.custom_service_qq]];
        }
    }];
}
-(void)backBtnClicked{
    [self.webView stopLoading];
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [super backBtnClicked];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)dealloc {
    [_jsHandler cancelHandler];
    self.webView.navigationDelegate = nil;
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
@end
